<template>
  <div class="order-container">
    <el-tabs @tab-change="tabChange">
      <!-- tab切换 -->
      <el-tab-pane v-for="item in tabTypes" :key="item.name" :label="item.label" />

      <div class="main-container">
        <div class="holder-container" v-if="orderList.length === 0">
          <el-empty description="暂无订单数据" />
        </div>
        <div v-else>
          <!-- 订单列表 -->
          <div class="order-item" v-for="order in orderList" :key="order.id">
            <div class="head">
              <span>下单时间：{{ order.createTime }}</span>
              <span>订单编号：{{ order.id }}</span>
            </div>
            <div class="body">
              <div class="column goods">
                <ul>
                  <li v-for="item in order.orderGoodsList" :key="item.id">
                    <a class="image" href="javascript:;">
                      <img :src="item.picture" alt="" />
                    </a>
                    <div class="info">
                      <p class="name ellipsis-2">{{ item.name }}</p>
                      <p class="attr ellipsis">
                        <span>{{ item.attrsText }}</span>
                      </p>
                    </div>
                    <div class="price">¥{{ item.price?.toFixed(2) }}</div>
                    <div class="count">x{{ item.count }}</div>
                  </li>
                </ul>
              </div>
              <div class="column amount">
                <p class="red">¥{{ order.totalMoney?.toFixed(2) }}</p>
                <p>在线支付</p>
              </div>
              <div class="column action">
                <el-button v-if="order.orderState === 0" type="primary" size="small"
                  @click="payOrder(order.id, order.payChannel)">
                  立即付款
                </el-button>
                <el-button v-if="order.orderState === 4" type="primary" size="small" @click="confirmReceive(order.id)">
                  确认收货
                </el-button>
                <el-button v-if="order.orderState === 5" type="primary" size="small"
                  @click="openCommentDialog(order.id, order.orderGoodsList)">
                  评论
                </el-button>
                <p><a href="javascript:;">查看详情</a></p>
                <p v-if="[0, 1, 2, 3, 4].includes(order.orderState)">
                  <el-popconfirm title="确认取消吗？" confirm-button-text="确认" cancel-button-text="取消"
                    @confirm="cancelOrder(order.id)">
                    <template #reference>
                      <a href="javascript:;">取消订单</a>
                    </template>
                  </el-popconfirm>
                </p>
              </div>
            </div>
          </div>
          <!-- 分页 -->
          <div class="pagination-container">
            <el-pagination :total="total" @current-change="pageChange" :page-size="params.pageSize" background
              layout="prev, pager, next" />
          </div>
        </div>
      </div>
    </el-tabs>
  </div>

  <!-- 评论弹窗 -->
  <el-dialog v-model="commentDialogVisible" title="评论" width="30%">
    <el-form :model="commentForm" :rules="commentRules" ref="commentFormRef" label-width="80px">
      <el-form-item label="选择商品" prop="skuId">
        <el-select v-model="commentForm.skuId" placeholder="请选择要评论的商品">
          <el-option
            v-for="item in selectedOrderGoodsList"
            :key="item.id"
            :label="`${item.name}（${item.attrsText}）`"
            :value="item.skuId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="是否匿名">
        <el-radio-group v-model="isAnonymous" @change="handleAnonymousChange">
          <el-radio :label="true">匿名</el-radio>
          <el-radio :label="false">不匿名</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="内容" prop="content">
        <el-input v-model="commentForm.content" type="textarea" />
      </el-form-item>
      <el-form-item label="评分" prop="rating">
        <el-rate v-model="commentForm.rating" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="commentDialogVisible = false">取消</el-button>
      <el-button type="primary" @click="submitComment">提交</el-button>
    </template>
  </el-dialog>

  <PayDrawer ref="drawer" />
</template>

<script setup>
import { getUserOrder } from '@/apis/order';
import { ElMessage } from "element-plus";
import { onMounted, ref } from 'vue';
import { userCancelOrderAPI, confirmReceiveAPI, commentOrderAPI } from "@/apis/order.js";
import { useUserStore } from "@/stores/userStore";
import PayDrawer from "@/views/user/Pay/components/PayDrawer.vue";

const userStore = useUserStore();

// tab列表
const tabTypes = [
  { label: "全部订单", value: '' },
  { label: "待付款", value: 0 },
  { label: "待发货", value: 1 },
  { label: "已发货", value: 2 },
  { label: "运输中", value: 3 },
  { label: "已收货", value: 4 },
  { label: "已完成", value: 5 },
  { label: "取消中", value: 6 },
  { label: "已取消", value: 7 }
];

// 获取订单列表
const orderList = ref([]);
const total = ref(0);
const params = ref({
  orderState: '',
  page: 1,
  pageSize: 2
});
const drawer = ref();

const getOrderList = async () => {
  const res = await getUserOrder(params.value);
  orderList.value = res.data.records;
  total.value = res.data.total;
};

const payOrder = (id, payChannel) => {
  drawer.value.pay(id, payChannel);
};

onMounted(() => getOrderList());

// tab切换
const tabChange = (typeIndex) => {
  const selectedTab = tabTypes[typeIndex];
  params.value.orderState = selectedTab.value;
  getOrderList();
};

// 取消订单
const cancelOrder = async (id) => {
  const res = await userCancelOrderAPI(id);
  if (res.code === 1) {
    ElMessage.success("已取消");
    getOrderList();
  }
};

// 确认收货
const confirmReceive = async (id) => {
  const res = await confirmReceiveAPI(id);
  if (res.code === 1) {
    ElMessage.success("已确认");
    getOrderList();
  }
};

const commentDialogVisible = ref(false);
const commentForm = ref({
  orderId: '',
  skuId: '',
  userName: userStore.userInfo.name,
  content: '',
  rating: 0
});

const isAnonymous = ref(false); // 默认选择不匿名
const handleAnonymousChange = () => {
  if (isAnonymous.value) {
    // 如果选择匿名
    commentForm.value.userName = '匿名';
  } else {
    // 如果选择不匿名
    commentForm.value.userName = userStore.userInfo.name;
  }
};

const selectedOrderGoodsList = ref([]); // 当前订单的商品列表
// 打开评论弹窗
const openCommentDialog = (id, orderGoodsList) => {
  selectedOrderGoodsList.value = orderGoodsList;
  commentForm.value.orderId = id;
  commentDialogVisible.value = true;
};

// 表单验证规则
const commentRules = {
  skuId: [{ required: true, message: '请选择要评论的商品', trigger: 'blur' }],
  content: [{ required: true, message: '请输入评论内容', trigger: 'blur' }],
  rating: [{ required: true, message: '请选择评分', trigger: 'blur' }]
};

const commentFormRef = ref(null);

// 提交评论
const submitComment = async () => {
  try {
    await commentFormRef.value.validate();
    const res = await commentOrderAPI(commentForm.value);

    if (res.code === 1) {
      ElMessage.success("评论成功");
      commentDialogVisible.value = false;
      getOrderList();
    }
  } catch (error) {
    ElMessage.error("请填写完整信息");
  }
};

// 页数切换
const pageChange = (page) => {
  params.value.page = page;
  getOrderList();
};

// 订单状态格式化
const fomartPayState = (payState) => {
  const stateMap = {
    0: '待付款',
    1: '待发货',
    2: '已发货',
    3: '运输中',
    4: '已收货',
    5: '已完成',
    6: '取消中',
    7: '已取消',
  };
  return stateMap[payState];
};
</script>

<style scoped>
.order-container {
  padding: 10px 20px;
}

.pagination-container {
  display: flex;
  justify-content: center;
}

.main-container {
  min-height: 500px;
}

.holder-container {
  min-height: 500px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.order-item {
  margin-bottom: 20px;
  border: 1px solid #f5f5f5;
}

.head {
  height: 50px;
  line-height: 50px;
  background: #f5f5f5;
  padding: 0 20px;
  overflow: hidden;
}

.head span {
  margin-right: 20px;
}

.body {
  display: flex;
  align-items: stretch;
}

.column {
  border-left: 1px solid #f5f5f5;
  text-align: center;
  padding: 20px;
}

.column:first-child {
  border-left: none;
}

.goods {
  flex: 1;
  padding: 0;
  align-self: center;
}

.goods ul li {
  border-bottom: 1px solid #f5f5f5;
  padding: 10px;
  display: flex;
}

.goods ul li:last-child {
  border-bottom: none;
}

.image {
  width: 70px;
  height: 70px;
  border: 1px solid #f5f5f5;
}

.info {
  width: 220px;
  text-align: left;
  padding: 0 10px;
}

.info p {
  margin-bottom: 5px;
}

.name {
  height: 38px;
}

.attr {
  color: #999;
  font-size: 12px;
}

.price {
  width: 100px;
}

.count {
  width: 80px;
}

.amount {
  width: 200px;
}

.red {
  color: #f56c6c;
}

.action {
  width: 140px;
}

.action a {
  display: block;
}

.action a:hover {
  color: #409eff;
}
</style>